import {AnswerControllerService, AnswerFlowService} from "./service";

@Midway.MidwayModule({
    code: "AnswerFlowController",
    dependLibs: ['message']
})
class AnswerFlowController extends CommonController {

    constructor() {
        super();
        this.metaInfo.name = 'AnswerFlowController';
        this.metaInfo.type = ConstVariable.PresenterType.CONTROLLER;

        this.answerIntercept = [];
        this.questionServiceList = [];
        //提交过的答案
        this.answerSumbit = {};
        //标记是否曾经提交成功过,默认为false
        this.hasSuccessSubmit = false;
        this.timerService = null;
        this.submitButtonService = null;
        this.answerFlowStatus = answerFlowStatus.STATUS_INIT;
        this.state = {};
        //在提交答案后,是否需要显示答案
        this.showResultOnSubmit = false;
        //是否加载发送到学生端的组件, 默认为True
        this.loadSendQuestion = true;
        //学生端是否时间结束
        this.isTimeOver = false;
        this.appEnv = undefined;
        this.sendToStudentService = null;
        this.linkQuestionId = undefined;
        //多语言Key列表
        this.languageKeySet = {};
        this.service = undefined;
        this.ControlService = new AnswerControllerService(this);
    }

    getService() {
        if(this.service === undefined) {
            this.service = new AnswerFlowService();
        }
        return this.service;
    }

    $launch() {
        if (this.Model.showResultOnSubmit != undefined &&
            (this.Model.showResultOnSubmit === true || this.Model.showResultOnSubmit === 'true')) {
            this.showResultOnSubmit = true;
        }
        if (this.Model.loadSendQuestion != undefined &&
            (this.Model.loadSendQuestion === false || this.Model.loadSendQuestion === 'false')) {
            this.loadSendQuestion = false;
        }
        if (this.QueryString["loadSendQuestion"] && this.QueryString["loadSendQuestion"] == 'false') {
            this.loadSendQuestion = false;
        }
        if (this.QueryString["app"]) {
            this.appEnv = this.QueryString["app"];
        }
        if (this.Model.linkQuestionId != undefined) {
            this.linkQuestionId = this.Model.linkQuestionId;
        }
        this._bindEvent();
    }

    $release() {
        this._unbindEvent();
    }

    _bindEvent() {
        //单题目的状态发生变化
        this.addEventListener(answerFlowEvent.QUESTION_STATE_CHANGE,
            ConstVariable.PresenterEventType.IC_PLAYER_EVENT, this._onQuestionStateChanged);
        //嵌入题目的状态发送变化
        this.addEventListener(answerFlowEvent.EMBEDDED_QUESTION_STATE_CHANGE,
            ConstVariable.PresenterEventType.IC_PLAYER_EVENT, this._onEmbeddedQuestionStateChanged);
        //提交事件
        this.addEventListener("custom_event_submit_answer",
            ConstVariable.PresenterEventType.IC_PLAYER_EVENT, this._onQuestionSubmit);
        this.addEventListener(answerFlowEvent.AUTO_SEND_ANSWER,
            ConstVariable.PresenterEventType.IC_PLAYER_EVENT, this._onQuestionSubmit);

        if (this.isApp && this.isStudent) {
            this.addEventListener(answerFlowEvent.SEND_ANSWER_CALLBACK,
                ConstVariable.PresenterEventType.IC_PLAYER_EVENT, this._onQuestionSubmitCallback);
            this.addEventListener(answerFlowEvent.SEND_ANSWER_STOP,
                ConstVariable.PresenterEventType.IC_PLAYER_EVENT, this._onStopQuestion);
        }

        if (this.embedApplication('pptshell') || this.Environment.isPC) {
            this.addEventListener(answerFlowEvent.EXERCISE_STATE_CHANGE,
                ConstVariable.PresenterEventType.IC_PLAYER_EVENT, this._onExerciseStateChanged);
        }

        var self = this;
        //注册一个可以显示正确答案的流
        if (this.embedApplication('pptshell') || this.Environment.isWeb) {
            //注册一个业务流, 用于在预览时显示正确答案
            this.PlayerController.registerFlow(answerFlowEvent.PREVIEW_SHOW_CORRECT_ANSWER, {
                scope: 'page',
                validate: function (data) {
                    var defaultOption = {
                        finish: true,
                        whoAnswer: 'correct',
                        specialAnswer: undefined,
                        context: self
                    };
                    if (data == undefined) {
                        return defaultOption;
                    } else {
                        return $.extend(defaultOption, data);
                    }
                },
                done: self._whenPreviewAnswerDone
            });
        }

        //注册一个业务流, 用于接送来自外部对题目状态的设置
        this.PlayerController.registerFlow(answerFlowEvent.SET_QUESTION_STATUS, {
            scope: 'page',
            validate: function (data) {
                var defaultOption = {
                    status: 'reset',
                    options: {
                        timer: 'continue'
                    }
                };
                if (data == undefined) {
                    return defaultOption;
                } else {
                    return $.extend(defaultOption, data);
                }
            },
            done: function (option) {
                switch (option.status) {
                    case 'reset':
                        self._changeQuestionState({'resetQuestion': {}});
                        self.submitButtonService.setButtonState(buttonStatus.RESET);
                        break;
                    case 'lock':
                        self._changeQuestionState({'lockQuestion': {}});
                        self.submitButtonService.setButtonState(buttonStatus.CAN_NOT_SUBMIT);
                        break;
                    case 'unlock':
                        self._changeQuestionState({'unlockQuestion': {}});
                        break;
                    case 'finish':
                        self._changeQuestionState({'finishQuestion': {}});
                        self.submitButtonService.setButtonState(buttonStatus.FINISH);
                        break;
                    case 'reflow':
                        if (self.isStudent) {
                            self.hasSuccessSubmit = false; //需要初始化此变量，否则一个学生继续作答了但未能提交，继续作答结果将无法发送给老师端
                            self._changeQuestionState({'unlockQuestion': {}}); //学生端解锁，学生继续作答
                        } else {
                            self._changeQuestionState({'resetQuestion': {}, 'lockQuestion': {}}); //老师端重置并锁定
                        }
                        self.submitButtonService && self.submitButtonService.setButtonState(buttonStatus.CAN_NOT_SUBMIT);
                        if (option.options.timer === 'continue') {
                            if (self.timerService) {
                                if (self.isStudent) { //同步教师端时间
                                    self.timerService.start(true, option.redoTimestamp);
                                } else {
                                    self.timerService.start();
                                }
                            }
                        }
                        break;
                }
            }
        });
    }

    _unbindEvent() {
        this.$removeEventListener();
    }

    /*以下是事件处理的私有方法*/
    _whenPreviewAnswerDone(option) {
        var self = option.context;
        if (option.finish == true) {
            //停止时间
            if (self.timerService) {
                self.timerService.stop();
            }
            //设置按钮状态, 为结束作答
            self.submitButtonService.setButtonState(buttonStatus.RESET);
        }
        if (self.questionServiceList && self.questionServiceList.length > 0) {
            //将所有的题型显示答案
            $.each(self.questionServiceList, function (index, item) {
                item.lockQuestion();
                switch (option.whoAnswer) {
                    case 'correct':
                    case 'user':
                        item.showAnswer(option.whoAnswer);
                        break;
                    case 'special':
                        if (option.specialAnswer != undefined) {
                            item.showAnswer('user', option.specialAnswer);
                        } else {
                            item.showAnswer('user');
                        }
                }
            });
        }
    }

    /*发送到学生端相关的方法结束*/
    // 随堂练习状态变更
    _onExerciseStateChanged(eventData) {
        switch (eventData.type) {
            case 'start':
                this._onExerciseStart(eventData.value);
                break;
            case 'stop':
                this._onExerciseStop(eventData.value);
                break;
            case 'exit':
                this._onExerciseExit(eventData.value);
                break;
            //教师点击结束的时候
            case 'mockStop':
                if (this.timerService && eventData.value.result == true) {
                    this.timerService.pause(false);
                }
                break;
            //教师点击发送题目的时候
            case 'mockStart':
                if (this.timerService && eventData.value.result == true) {
                    this.timerService.pause(false);
                }
                //如果存在发送按钮,将发送按钮隐藏
                if (this.sendToStudentService != null) {
                    this.sendToStudentService.setVisible(false);
                }
                break;
            default:
                this.Logger.debug("未知的随堂练习状态变更数据：" + JSON.stringify(eventData));
                break;
        }
    }

    _onExerciseStart(data) {
        //发送题目失败
        if (data.result == false) {
            this.Logger.info('发送题目失败!');
            if (this.timerService) {
                this.timerService.start(false);
            }
            //如果存在发送按钮,将发送按钮显示
            if (this.sendToStudentService != null) {
                this.sendToStudentService.setVisible(true);
            }
        } else {
            //发送题目时,把PPTShell上提交按钮隐藏, 同时显示遮罩层
            if (this.submitButtonService) { //针对个别题型（如：思维导图），老师端没有提交按钮
                this.submitButtonService.setVisible(false);
            }
            //发题成功后重置教师端的题目状态
            this._changeQuestionState({'lockQuestion': {}, 'resetQuestion': {}});
            //处理时间组件
            if (this.timerService) {
                this.timerService.stop();
                if (data.startTimestamp != undefined) {
                    this.timerService.start(true, data.startTimestamp);
                } else {
                    this.timerService.start(true);
                }
            }
        }
    }

    _onExerciseStop(data) {
        if (data.result == false) {
            //结束练习失败
            this.Logger.info('结束题目失败!');
            if (this.timerService) {
                this.timerService.start(false);
            }
        } else {
            // 结束练习
            this.Logger.debug("结束练习,锁定题目");
            if (this.timerService) {
                this.timerService.stop();
            }
            this._changeQuestionState({'unlockQuestion': {}});
        }
    }

    _onExerciseExit(data) {
        //重置题目, 设置按钮为可见, 同时解锁题型
        this._changeQuestionState({'unlockQuestion': {}, 'resetQuestion': {}, 'finishQuestion': {}});
        if (this.submitButtonService) {
            this.submitButtonService.setVisible(true);
        }
        //设置按钮的状态为不可作答
        if (this.submitButtonService) {
            this.submitButtonService.setButtonState(buttonStatus.CAN_NOT_SUBMIT);
        }
        //重置计时器
        //处理时间组件
        if (this.timerService) {
            this.timerService.stop();
            this.timerService.start(false);
        }
        //如果存在发送按钮,将发送按钮显示出来
        if (this.sendToStudentService != null) {
            this.sendToStudentService.setVisible(true);
        }
    }

    // 按钮状态变更
    _onQuestionStateChanged(eventData) {
        if (eventData === undefined) {
            return;
        }
        //如果事件中的关联ID和组件中的linkQuestionId都不为undefined的话
        if (eventData.linkQuestionId != undefined && this.linkQuestionId != undefined) {
            if (eventData.linkQuestionId != this.linkQuestionId) {
                return;
            }
        }
        if (this.submitButtonService) {
            var buttonState = this.submitButtonService.getState().code;
            if (buttonState == buttonStatus.CAN_NOT_SUBMIT && eventData.canSubmit) {
                this.Logger.debug("习题状态变更为「可提交」");
                this.submitButtonService.setButtonState(buttonStatus.CAN_SUBMIT);
            }
            if (buttonState == buttonStatus.MODIFY_SUBMIT && eventData.canSubmit) {
                this.Logger.debug("习题状态变更为「修改后，重新提交」");
                this.submitButtonService.setButtonState(buttonStatus.RETRY_SUBMIT);
            }
            if (buttonState == buttonStatus.MODIFY_SUBMIT && !eventData.canSubmit) {
                this.Logger.debug("习题状态变更为「重新提交, 但无法点击」");
                this._changeQuestionState({'unlockQuestion': {}});
            }
            if ((buttonState == buttonStatus.CAN_SUBMIT || buttonState == buttonStatus.RETRY_SUBMIT)
                && !eventData.canSubmit) {
                this.Logger.debug("习题状态变更为「不可提交」");
                this.submitButtonService.setButtonState(buttonStatus.CAN_NOT_SUBMIT);
            }
        }
    }

    //嵌入题目的状态变化
    _onEmbeddedQuestionStateChanged(eventData) {
        if (eventData === undefined) {
            return;
        }
        if (this.submitButtonService) {
            var buttonState = this.submitButtonService.getState().code;
            if (buttonState == buttonStatus.CAN_NOT_SUBMIT && eventData.canSubmit) {
                this.Logger.debug("习题状态变更为「可提交」");
                this.submitButtonService.setButtonState(buttonStatus.CAN_SUBMIT);
            }
            if (buttonState == buttonStatus.MODIFY_SUBMIT && eventData.canSubmit) {
                this.Logger.debug("习题状态变更为「修改后，重新提交」");
                this.submitButtonService.setButtonState(buttonStatus.RETRY_SUBMIT);
            }
            if (buttonState == buttonStatus.MODIFY_SUBMIT && !eventData.canSubmit) {
                this.Logger.debug("习题状态变更为「重新提交, 但无法点击」");
                this._changeQuestionState({'unlockQuestion': {}});
            }
        }
    }

    //由提交按钮触发的提交行为
    _onQuestionSubmit(eventData, eventName) {
        //获得作答结果
        if (!eventData.question_id) {
            throw new Error();
        }
        //如果不存在提交按钮的状态;获取提交按钮的当前状态
        if (!eventData.state) {
            eventData.state = this.submitButtonService.getButtonState();
        }
        //从托管的Presenter中获取类型为'题型'的presenter
        var self = this;
        var deferreds = this._getQuestionAnswer();
        $.when.apply($, deferreds)
            .done(function () {
                var result = {
                    answers: {},
                    spendTime: -1
                };
                //获取消耗的时间
                if (self.timerService != null) {
                    result.spendTime = self.timerService.getTimeValue();
                }
                //压入处理堆栈
                $.each(arguments, function (index, item) {
                    result.answers[item.key] = item.value;
                    //记录提交记录
                    self.answerSumbit[item.key] = item.value;
                });
                //后续处理流程
                self._handleQuestionSubmit.call(self, result, eventData, eventName);
            });
    }

    //处理题目提交的交互流程
    _handleQuestionSubmit(result, eventData, eventName) {
        var questionAnswer = result.answers[eventData.question_id];
        this.Logger.debug("开始主动提交答案了", questionAnswer);
        //是否为自动作答
        var isAutoSend = (eventName == answerFlowEvent.AUTO_SEND_ANSWER);
        //如果当前运行状态不为学生Pad
        //如果是PC端或PPTShell端,显示提交答案的提示
        if (this.embedApplication('pptshell') || this.Environment.isPC || this.Environment.isWeb) {
            //获取弹窗
            var popDialog = this.LayoutService.getContainer('MessagePanel');
            var self = this;
            //如果是重新作答的情景
            if (eventData.state == buttonStatus.RESET) {
                //设置按钮的状态
                if (this.submitButtonService) {
                    this.submitButtonService.setButtonState(buttonStatus.CAN_NOT_SUBMIT);
                }
                //重置Timer
                if (this.timerService) {
                    this.timerService.stop();
                    this.timerService.start(false);
                }
                //重置题目
                this._changeQuestionState({'unlockQuestion': {}, 'resetQuestion': {}});
                return;
            }
            //锁定题目
            this._changeQuestionState({'lockQuestion': {}});
            if (eventName == "custom_event_submit_answer") {
                //正常的点击按钮事件
                MessageBoxRemake.showPop(popDialog, {
                    mode: 'wood',
                    type: 'confirm',
                    text: this._getLanguageText('submit_answer'),
                    buttons: [{
                        text: this._getLanguageText('submit_confirm'),
                        handle: function () {
                            self._handleAnswerInPPT.call(self, questionAnswer, popDialog);
                        }
                    }, {
                        text: this._getLanguageText('submit_cancel'),
                        handle: function () {
                            $(popDialog).hide();
                            //解锁题目
                            self._changeQuestionState({'unlockQuestion': {}});
                            if (self.submitButtonService) {
                                self.submitButtonService.setButtonState(self.submitButtonService.getState().code);
                            }
                        }
                    }]
                });
            } else if (eventName == answerFlowEvent.AUTO_SEND_ANSWER) {
                //自动提交的处理
                self._handleAnswerInPPT(questionAnswer, popDialog);
            }
            $(popDialog).show();
        } else {
            // 按钮点击事件处理
            this._onSubmitButtonClick(eventData.state, eventData.question_type, questionAnswer, isAutoSend);
        }
    }

    //处理在PPTShell上的作答流程
    _handleAnswerInPPT(questionAnswer, popDialog) {
        var self = this;
        //停止时间
        if (self.timerService) {
            self.timerService.stop();
        }
        //设置按钮状态, 为结束作答
        self.submitButtonService.setButtonState(buttonStatus.RESET);
        //判断是否作答正确
        if (questionAnswer.answer.answer_result) {
            //如果作答正确
            MessageBoxRemake.showPop(popDialog, {
                mode: "wood",
                type: "right",
                text: self._getLanguageText('answer_right')
            });
        } else {
            //如果作答错误
            MessageBoxRemake.showPop(popDialog, {
                mode: "wood",
                type: "error",
                text: self._getLanguageText('answer_wrong')
            });
        }
        self._showAnswer(questionAnswer.questionId, questionAnswer);

    }

    // 提交答案回调
    _onQuestionSubmitCallback(data) {
        if (data.item == 'nosubmit') {
            // 不提交时，无需反馈
            return;
        }
        // 改变按钮状态
        var value = data.value;
        var submitResult = value.result;
        var targetState;

        if (this.state.isFinish) {
            // 不论成功与否，均显示「已结束」
            targetState = buttonStatus.FINISH;
            //设置当前流程状态已经公布答案
            this.answerFlowStatus = answerFlowStatus.STATUS_PUBLISH_ANSWER;
        } else {
            var hintText = '';
            if (submitResult) {
                // 提交成功，显示「修改」
                targetState = buttonStatus.CAN_MODIFY;
                //设置当前流程状态为已经提交
                this.answerFlowStatus = answerFlowStatus.STATUS_ANSWER_OVER;
                hintText = this._getLanguageText('submit_successfully');
                this.hasSuccessSubmit = true; //表示本次提交是成功的
            } else {
                // 提交失败，显示「重新提交」
                targetState = buttonStatus.RETRY_SUBMIT;
                hintText = this._getLanguageText('submit_failed');
            }
            //调用Native的Toast提示
            this.dispatchEvent('showMessageBox', ConstVariable.PresenterEventType.NATIVE_EVENT, {
                item: 'open',
                value: {
                    text: hintText,
                    layout: ['center', 'center'],
                    type: 'gray',
                    timeout: 2000
                }
            });
        }
        if (this.submitButtonService) {
            this.submitButtonService.setButtonState(targetState);
        }
        //调用有实现作答提交接口的服务
        $.each(this.answerIntercept, function (key, item) {
            item.afterSendAnswer(value);
        });
    }

    // 收卷
    _onStopQuestion(data) {
        if (this.questionServiceList.length == 0) {
            this.Logger.debug("没有QuestionService, 不做后面的事情了");
            return;
        }
        this.Logger.debug("结束练习");
        // 重置按钮状态
        if (this.submitButtonService) {
            this.submitButtonService.setButtonState(buttonStatus.FINISH);
        }
        // 结束计时
        if (this.timerService) {
            if (data.value && data.value.stopTimestamp > 0) {
                this.timerService.setTimeValue(data.value.stopTimestamp);
            }
            this.timerService.stop();
        }
        if (data.isForceStop) {
            // 强制收卷，不提交答案
            return;
        }
        // 其他情况下，提交答案
        this._onFinishAnswer({isFinish: true, isTimeOver: false});
    }

    // 点击提交按钮
    _onSubmitButtonClick(buttonState, questionType, questionAnswer, isAutoSend) {
        this.Logger.debug("按钮状态：" + buttonState);
        switch (buttonState) {
            case buttonStatus.CAN_MODIFY: // 修改
                this._onModify(questionType); // 切换到可修改状态
                break;
            case buttonStatus.CAN_SUBMIT: // 提交
            case buttonStatus.RETRY_SUBMIT: // 重新提交
                // 提交答案
                this._onSendAnswer({
                    questionType: questionType,
                    questionAnswer: questionAnswer,
                    isAutoSend: isAutoSend
                });
                break;
            case buttonStatus.SUBMITTING: // 提交中
            case buttonStatus.CAN_NOT_SUBMIT: // 不能提交
            case buttonStatus.FINISH: // 已结束
            default:
                break;
        }
    }

    // 切换到可修改的状态
    _onModify(questionType) {
        // 解锁题目
        this._changeQuestionState({'unlockQuestion': {}});

        if (this.submitButtonService) {
            this.Logger.debug('互动题型控制器：点击修改按钮，按钮状态变更为灰态的「提交」');
            this.submitButtonService.setButtonState(buttonStatus.MODIFY_SUBMIT);
        }
        //重新开始计时
        if (this.timerService != null) {
            this.timerService.start(true);
        }
        //设置流程状态为初始状态,可提交答案
        this.answerFlowStatus = answerFlowStatus.STATUS_INIT;
        if ($PresenterEvent['InteractionStateRecoverFilter']) {
            this.dispatchEvent($PresenterEvent['InteractionStateRecoverFilter'].PRESENTER_STATE_CHANGE,
                ConstVariable.PresenterEventType.IC_PLAYER_EVENT, {});
        }
    }

    // 提交答案
    _onSendAnswer(options) {
        //获取题型和题型的答案
        //var questionType = options.questionType;
        var questionAnswer = options.questionAnswer;
        //自动发送
        var isAutoSend = options.isAutoSend;
        this.Logger.debug("互动题型控制器：提交答案，参数：" + JSON.stringify(options));
        this.state.isFinish = options.isFinish || false;
        this.state.isTimeOver = options.isTimeOver || false;
        this.Logger.debug("互动题型控制器：当前习题答案：" + JSON.stringify(questionAnswer));
        // 如果答案为空，则无法提交
        if (questionAnswer === undefined || questionAnswer.answer === undefined) {
            this.Logger.debug("互动题型控制器：答案为空，无法提交");
            return;
        }
        this.Logger.debug('互动题型控制器：提交答案开始');
        //锁定题目
        this._changeQuestionState({'lockQuestion': {}});
        this.Logger.debug('互动题型控制器：提交答案中，按钮状态变更为「提交中」');
        if (this.submitButtonService) {
            this.submitButtonService.setButtonState(buttonStatus.SUBMITTING);
        }
        var sendData = {
            questionId: questionAnswer.questionId,
            answer: questionAnswer.answer
        };
        //如果存在作答状态, 且作答状态为false
        if (questionAnswer.answerState != undefined &&
            (questionAnswer.answerState === false || questionAnswer.answerState === 'NO_ANSWER')) {
            sendData.notSubmit = false;
            sendData.answer = '';
        }
        //在需要发送数据之前,将进行发送数据的拦截
        if (this.answerIntercept.length > 0) {
            $.each(this.answerIntercept, function (index, item) {
                //如果QuestionID相同, 将要发送的数据进行拦截处理
                if (item.getInterceptId() == questionAnswer.questionId) {
                    sendData = item.beforeSendAnswer(sendData);
                    return false;
                }
            });
        }
        // 学生端Pad将数据发送给学生端分发器
        this.dispatchEvent(answerFlowEvent.SEND_ANSWER,
            ConstVariable.PresenterEventType.IC_PLAYER_EVENT, sendData);
        this.Logger.debug('互动题型控制器：提交答案结束');
        //如果是自动发送或被设置为提交即显示答案; 显示结果提示
        if (isAutoSend || this.showResultOnSubmit) {
            var spendTime = 0;
            if (this.timerService) {
                spendTime = this.timerService.getTimeValue();
            }
            this.Logger.debug('_onSendAnswer执行showResultHint');
            $.each(this.questionServiceList, function (index, item) {
                item.showAnswer("user");
                item.showResultHint({
                    trigger: "user",
                    spendTime: spendTime,
                    notSubmit: false
                });
            });
        }
    }

    //当前环境是PPTShell,在倒计时结束时;触发强制收题流程
    _forceStopAnswer() {
        var option = {
            type: "stop"
        };
        this.dispatchEvent("QuizProcess", ConstVariable.PresenterEventType.IC_PLAYER_EVENT, option);
    }

    /**
     * 当教师端结束作答时
     * 在教师端结束作答时,应该将当前页面上所有题目的作答结果都进行上报;
     * 目前的场景Page一般只包含唯一的互动题型;如果包含多个题型这个方法需要修改
     * */
    _onFinishAnswer(options) {
        if (options) {
            this.Logger.debug("互动题型控制器：结束作答，参数：" + JSON.stringify(options));
            this.state.isFinish = options.isFinish || false;
            //this.state.isTimeOver = options.isTimeOver || false;
            this.state.isTimeOver = this.isTimeOver;
        }
        var self = this;
        var timerOver = this.state.isTimeOver;
        var deferreds = this._getQuestionAnswer();
        $.when.apply($, deferreds)
            .done(function () {
                self.Logger.debug("开始获取答案");
                var questionAnswer = null;
                //只获取第一个
                $.each(arguments, function (index, item) {
                    questionAnswer = item.value;
                    return false;
                });
                self.Logger.debug("开始提交答案了");
                if (questionAnswer === undefined) {
                    self.Logger.debug("获取不到questionType和questionAnswer，无法提交答案");
                    return;
                }
                self.Logger.debug('互动题型控制器：提交答案开始');
                //锁定题目
                self._changeQuestionState({'lockQuestion': {}});
                self.Logger.debug('互动题型控制器：按钮状态变更为「已结束」');
                self.submitButtonService.setButtonState(buttonStatus.FINISH);
                //将时间进行停止
                var spendTime = 0;
                if (self.timerService) {
                    self.timerService.stop();
                    spendTime = self.timerService.getTimeValue();
                }
                //用户是否操作过
                var hasOperate = (questionAnswer.answerState === true || questionAnswer.answerState !== 'NO_ANSWER');
                var sendData = {questionId: questionAnswer.questionId, answer: ""};
                var resetAnswer = true;
                //如果是未作答状态
                if (!hasOperate) {
                    self.Logger.debug('未作答,hasOperate为false');
                    sendData.notSubmit = true;
                } else {
                    //如果处于非未作答情况
                    if (self.hasSuccessSubmit == false) {
                        //如果用户不曾提交成功过
                        self.Logger.debug('用户有作答,但没有提交过答案,需要提交答案!');
                        sendData.spendTime = spendTime;
                        sendData.answer = questionAnswer.answer;
                    } else {
                        //如果用户曾经提交过,结束作答过程不做任何事情
                        self.Logger.debug('用户已经提交过,不需要重复提交!');
                        sendData.notSubmit = true;
                        //设置不需要重置答案
                        resetAnswer = false;
                    }
                }
                //发送数据
                if (resetAnswer == true) {
                    //需要重置缓存的答案
                    self.answerSumbit[questionAnswer.questionId] = questionAnswer;
                }
                // 学生端Pad将数据发送给学生端分发器
                self.Logger.debug('开始发送作答结果');
                //在需要发送数据之前,将进行发送数据的拦截
                if (self.answerIntercept.length > 0) {
                    $.each(self.answerIntercept, function (index, item) {
                        //如果QuestionID相同, 将要发送的数据进行拦截处理
                        if (item.getInterceptId() == questionAnswer.questionId) {
                            sendData = item.beforeSendAnswer(sendData);
                            return false;
                        }
                    });
                }
                self.dispatchEvent(answerFlowEvent.SEND_ANSWER,
                    ConstVariable.PresenterEventType.IC_PLAYER_EVENT, sendData);
                self.Logger.debug('互动题型控制器：收集答案结束');

                //如果已经提交过答案,且showResultOnSubmit=true时, 是不需要重复调用showAnswer和showResultHint的
                if (!(self.showResultOnSubmit == true && this.hasSuccessSubmit == false)) {
                    $.each(self.questionServiceList, function (index, item) {
                        var questionId = item.getQuestionInfo().id;
                        if (self.answerSumbit[questionId] != undefined) {
                            //如果作答过
                            item.showAnswer("user", self.answerSumbit[questionId]);
                        } else {
                            //如果没有作答过
                            item.showAnswer("user");
                        }
                        self.Logger.debug('_onFinishAnswer执行showResultHint', self.state);
                        item.showResultHint({
                            trigger: timerOver ? "timer" : "user",
                            spendTime: spendTime,
                            notSubmit: self.hasSuccessSubmit
                        });

                    });
                }
                self.Logger.debug('互动题型控制器：显示作答结果');
            });
    }

    _getQuestionAnswer() {
        //从托管的Presenter中获取类型为'题型'的presenter
        var deferreds = [];
        var self = this;
        //将所有题型的答案压入
        $.each(this.questionServiceList, function (index, item) {
            if (self.linkQuestionId != undefined) {
                if (item.getQuestionInfo().id != self.linkQuestionId) {
                    return true;
                }
            }
            //学生没有主动提交过答案
            var temp = item.getResult();
            //压入一个延迟对象
            var def = $.Deferred();
            deferreds.push(def);
            if (temp.answer.user_response.length == 1 && temp.answer.user_response[0]["then"]) {
                //获取作答结果, 如果结果需要异步获取
                temp.answer.user_response[0].then(function (data) {
                    temp.answer.user_response[0] = data;
                    def.resolve({key: temp.questionId, value: temp});
                    self.Logger.debug("处理延迟的答案结束", temp);
                });
            } else {
                //压入一个延迟对象,并马上进行resolve
                def.resolve({key: temp.questionId, value: temp});
                self.Logger.debug("处理非延迟的答案结束", temp);
            }
        });
        return deferreds;
    }

    /**
     * 执行题目的状态变化函数
     * @param runSequence 执行变化函数的顺序
     * @private
     */
    _changeQuestionState(runSequence) {
        if (runSequence == undefined) {
            this.Logger.error('题目状态变更顺序函数错误');
        }
        //将所有题型的作答进行重置
        $.each(this.questionServiceList, function (index, item) {
            $.each(runSequence, function (method, params) {
                if (item[method] != undefined && $.isFunction(item[method])) {
                    item[method].call(item, params);
                }
            });
        });
    }

    _showAnswer(id, answer) {
        //将所有的题型显示答案
        $.each(this.questionServiceList, function (index, item) {
            //找到需要显示答案的题目
            if (item.getQuestionInfo().id == id) {
                if (answer.answer.user_response) {
                    item.showAnswer("user", answer);
                } else {
                    item.showAnswer("correct");
                }
            }
        });
    }

    _getLanguageText(key) {
        if (this.languageKeySet[key] == undefined)
            return "ERROR";
        return this.languageKeySet[key];
    }
}

const buttonStatus = {
    CAN_NOT_SUBMIT: 'can_not_submit', //不可提交状态
    CAN_SUBMIT: 'can_submit', //正常可提交状态
    CAN_MODIFY: 'can_modify', //可修改状态
    RESET: 'reset', //重新作答
    FINISH: 'finish', //结束状态
    SUBMITTING: 'submitting', // 提交中状态，不可修改
    RETRY_SUBMIT: 'retry_submit', // 提交失败，重新提交
    MODIFY_SUBMIT: 'modify_submit'//修改后，重新提交
};

const answerFlowEvent = {
    SEND_ANSWER: 'sendAnswer',
    SEND_ANSWER_CALLBACK: 'sendAnswerCallback',
    SEND_ANSWER_STOP: 'sendAnswerStop',
    EXERCISE_STATE_CHANGE: 'exerciseStateChange',
    QUESTION_STATE_CHANGE: 'questionStateChange',
    EMBEDDED_QUESTION_STATE_CHANGE: 'embeddedQuestionStateChange',
    AUTO_SEND_ANSWER: 'autoSendAnswer',
    PREVIEW_SHOW_CORRECT_ANSWER: 'PreviewShowCorrectAnswer', //在预览界面显示答案的响应
    SET_QUESTION_STATUS: 'SetQuestionStatus' //设置题目的状态
};

const answerFlowStatus = {
    STATUS_INIT: "init",  //初始的状态, 可以提交答案
    STATUS_ANSWER_OVER: "answer_over", //答案已经提交,处于不可修改状态
    STATUS_PUBLISH_ANSWER: "publish_answer"  //答案已经公布
};